package com.wangdao.wechatmall.service.wx;

import com.wangdao.wechatmall.bean.bo.wx.WXOrderCommentBO;
import com.wangdao.wechatmall.bean.bo.wx.WXOrderGoodsBO;
import com.wangdao.wechatmall.bean.bo.wx.WXOrderBO;
import com.wangdao.wechatmall.bean.bo.wx.WXOrderSubmitBO;
import com.wangdao.wechatmall.bean.pojo.*;
import com.wangdao.wechatmall.bean.vo.wx.WXOrderDetailVO;
import com.wangdao.wechatmall.bean.vo.wx.WXOrderListVO;
import com.wangdao.wechatmall.mapper.*;
import com.wangdao.wechatmall.util.HandleOptionUtils;
import com.wangdao.wechatmall.util.MyPageHelper;
import com.wangdao.wechatmall.util.OrderStatusTextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liyongqiang
 * CreateDate 2021/7/12 10:24
 */

@Service
public class WXOrderServiceImpl implements WXOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public WXOrderListVO queryList(WXOrderBO orderBO) {
        WXOrderListVO orderListVO = new WXOrderListVO();
        OrderExample orderExample = new OrderExample();
        List<Order> orders = null;
        if (orderBO.getShowType() == 0) {
            orders = orderMapper.selectByExample(orderExample);
        } else if (orderBO.getShowType() == 1) {
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andOrderStatusEqualTo((short) 101);
            orders = orderMapper.selectByExample(orderExample);
        } else if (orderBO.getShowType() == 2) {
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andOrderStatusEqualTo((short) 201);
            orders = orderMapper.selectByExample(orderExample);
        } else if (orderBO.getShowType() == 3) {
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andOrderStatusEqualTo((short) 301);
            orders = orderMapper.selectByExample(orderExample);
        } else if (orderBO.getShowType() == 4) {
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andOrderStatusEqualTo((short) 401);
            orders = orderMapper.selectByExample(orderExample);
        }
        orderListVO.setCount(orders.size());
        //对orders进行分页
        MyPageHelper.startPage(orderBO);
        orderListVO.setTotalPages((int) Math.ceil(orders.size() / orderBO.getSize()));
        List<WXOrderListVO.DataDTO> dataDTOS = new ArrayList<>();
        for (Order order : orders) {
            WXOrderListVO.DataDTO dataDTO = new WXOrderListVO.DataDTO();
            //id赋值
            dataDTO.setId(order.getId());
            //groupin赋值
            dataDTO.setIsGroupin(false);
            //orderSn赋值
            dataDTO.setOrderSn(order.getOrderSn());
            //actualPrice赋值
            dataDTO.setActualPrice(order.getActualPrice());
            //orderStatus赋值
            dataDTO.setOrderStatusText(OrderStatusTextUtils.getOrderStatusText(order));
            //handleOption赋值
            dataDTO.setHandleOption(HandleOptionUtils.handleOptionDTO(order));

            List<WXOrderListVO.DataDTO.GoodsListDTO> goodsListDTOS = new ArrayList<>();
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
            criteria.andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
            List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            for (OrderGoods goods : orderGoods) {
                WXOrderListVO.DataDTO.GoodsListDTO goodsListDTO = new WXOrderListVO.DataDTO.GoodsListDTO();
                goodsListDTO.setId(goods.getId());
                goodsListDTO.setGoodsName(goods.getGoodsName());
                goodsListDTO.setPicUrl(goods.getPicUrl());
                goodsListDTO.setNumber(goods.getNumber());
                goodsListDTOS.add(goodsListDTO);
            }
            //goodsList赋值
            dataDTO.setGoodsList(goodsListDTOS);
            dataDTOS.add(dataDTO);
        }

        orderListVO.setData(dataDTOS);
        return orderListVO;
    }

    @Override
    public WXOrderDetailVO getDetail(Integer orderId) {
        WXOrderDetailVO orderDetailVO = new WXOrderDetailVO();

        Order order = orderMapper.selectByPrimaryKey(orderId);
        WXOrderDetailVO.OrderInfoDTO orderInfoDTO = new WXOrderDetailVO.OrderInfoDTO();
        orderInfoDTO.setConsignee(order.getConsignee());
        orderInfoDTO.setAddress(order.getAddress());
        orderInfoDTO.setAddTime(order.getAddTime());
        orderInfoDTO.setOrderSn(order.getOrderSn());
        orderInfoDTO.setActualPrice(order.getActualPrice());
        orderInfoDTO.setMobile(order.getMobile());
        orderInfoDTO.setOrderStatusText(OrderStatusTextUtils.getOrderStatusText(order));
        orderInfoDTO.setGoodsPrice(order.getGoodsPrice());
        orderInfoDTO.setCouponPrice(order.getCouponPrice());
        orderInfoDTO.setId(order.getId());
        orderInfoDTO.setFreightPrice(order.getFreightPrice());
        orderInfoDTO.setHandleOption(HandleOptionUtils.handleOptionDTO(order));
        orderDetailVO.setOrderInfo(orderInfoDTO);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        orderDetailVO.setOrderGoods(orderGoods);


        return orderDetailVO;
    }

    @Override
    public int prepay(Integer orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus((short) 201);
        order.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int update = orderMapper.updateByPrimaryKeySelective(order);
        return update;
    }

    @Override
    public int cancel(int id) {
        Order order = new Order();
        order.setId(id);
        order.setOrderStatus((short) 102);
        order.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int cancel = orderMapper.updateByPrimaryKeySelective(order);
        return cancel;
    }

    @Override
    public int delete(int id) {
        Order order = new Order();
        order.setId(id);
        order.setDeleted(true);
        order.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int delete = orderMapper.updateByPrimaryKeySelective(order);
        return delete;

    }

    @Override
    public int confirm(int id) {
        Order order = new Order();
        order.setId(id);
        order.setOrderStatus((short) 401);
        order.setConfirmTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int confirm = orderMapper.updateByPrimaryKeySelective(order);
        return confirm;
    }

    @Override
    public int refund(int id) {
        Order order = new Order();
        order.setId(id);
        order.setOrderStatus((short) 202);
        order.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int refund = orderMapper.updateByPrimaryKeySelective(order);
        return refund;
    }

    @Override
    public OrderGoods getGoods(WXOrderGoodsBO WXOrderGoodsBO) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(WXOrderGoodsBO.getOrderId()).andGoodsIdEqualTo(WXOrderGoodsBO.getGoodsId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoods.get(0);
    }

    @Override
    public int orderComment(WXOrderCommentBO commentBO) {
        Comment comment = new Comment();
        comment.setContent(commentBO.getContent());
        comment.setHasPicture(commentBO.getHasPicture());
        comment.setPicUrls(commentBO.getPicUrls());
        comment.setStar(commentBO.getStar());

        Date date = new Date();
        comment.setAddTime(date);
        comment.setUpdateTime(date);


        comment.setType((byte) 3);
        comment.setDeleted(false);
        OrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());
        orderGoods.setComment(1);
        //将comment属性变为1
        orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
        //将valueId赋值
        comment.setValueId(orderGoods.getGoodsId());
        Order order = orderMapper.selectByPrimaryKey(orderGoods.getOrderId());
        comment.setUserId(order.getUserId());
        int insert = commentMapper.insert(comment);
        return insert;
    }

    @Override
    public int orderSubmit(WXOrderSubmitBO submitBO) {
        //通过cartId取值
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        Order order = new Order();
        OrderGoods orderGoods = new OrderGoods();
        String orderSn = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        order.setOrderSn(orderSn);
        order.setOrderStatus((short) 101);
        order.setIntegralPrice(0.0);
        //通过addressId取值
        Address address = addressMapper.selectByPrimaryKey(submitBO.getAddressId());
        order.setConsignee(address.getName());
        order.setUserId(address.getUserId());
        order.setMobile(address.getMobile());
        order.setAddress(address.getAddress());
        order.setMessage(submitBO.getMessage());
        order.setGoodsPrice(0.0);
        order.setFreightPrice(0.0);
        order.setIntegralPrice(0.0);
        order.setGrouponPrice(0.0);
        order.setOrderPrice(0.0);
        order.setCouponPrice(0.0);
        order.setActualPrice(0.0);
        //将设置好的数据插入数据库
        int i = orderMapper.insertSelective(order);
        if (i == 0) {
            return 0;
        }
        //再从数据库中取出刚插入的orderId
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria1 = orderExample.createCriteria();
        criteria1.andUserIdEqualTo(address.getUserId()).andOrderSnEqualTo(orderSn);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Integer id = orders.get(0).getId();
        BigDecimal goodsPrice = null;
        BigDecimal freightPrice = null;
        BigDecimal couponPrice = null;
        BigDecimal orderPrice = null;
        BigDecimal actualPrice = null;
        int cartId = submitBO.getCartId();
        if (cartId == 0) {
            //取出cart数组
            criteria.andDeletedEqualTo(false).andCheckedEqualTo(true);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            for (Cart cart : carts) {
                if (goodsPrice == null) {
                    goodsPrice = cart.getPrice();
                } else {
                    goodsPrice = goodsPrice.add(cart.getPrice());
                }
                // 在orderGoods里加入数据
                orderGoods.setOrderId(id);
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setGoodsName(cart.getGoodsName());
                orderGoods.setGoodsSn(cart.getGoodsSn());
                orderGoods.setProductId(cart.getProductId());
                orderGoods.setNumber(cart.getNumber());
                orderGoods.setPrice(cart.getPrice());
                orderGoods.setSpecifications(cart.getSpecifications());
                orderGoods.setPicUrl(cart.getPicUrl());
                orderGoods.setComment(0);
                Date date = new Date();
                orderGoods.setAddTime(date);
                orderGoods.setUpdateTime(date);
                orderGoods.setDeleted(false);
                //将购物车里的订单清空
                Cart cart1 = new Cart();
                cart1.setId(cart.getId());
                cart1.setDeleted(true);
                cartMapper.updateByPrimaryKeySelective(cart1);
                //将orderGoods插入数据库中
                int insert = orderGoodsMapper.insertSelective(orderGoods);
                if (insert == 0) {
                    return 0;
                }
            }
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            goodsPrice = cart.getPrice();
            // 在orderGoods里加入数据
            orderGoods.setOrderId(id);
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setGoodsSn(cart.getGoodsSn());
            orderGoods.setProductId(cart.getProductId());
            orderGoods.setNumber(cart.getNumber());
            orderGoods.setPrice(cart.getPrice());
            orderGoods.setSpecifications(cart.getSpecifications());
            orderGoods.setPicUrl(cart.getPicUrl());
            orderGoods.setComment(0);
            Date date = new Date();
            orderGoods.setAddTime(date);
            orderGoods.setUpdateTime(date);
            orderGoods.setDeleted(false);
            //将购物车里的订单清空
            Cart cart1 = new Cart();
            cart1.setId(cart.getId());
            cart1.setDeleted(true);
            cartMapper.updateByPrimaryKeySelective(cart1);
            //将orderGoods插入数据库中
            int insert = orderGoodsMapper.insertSelective(orderGoods);
            if (insert == 0) {
                return 0;
            }
        }
        if (goodsPrice != null) {
            order.setGoodsPrice(goodsPrice.doubleValue());
        }
        if (goodsPrice.compareTo(BigDecimal.valueOf(100)) > -1) {
            freightPrice = BigDecimal.valueOf(0);
        } else {
            freightPrice = BigDecimal.valueOf(8);
        }
        order.setFreightPrice(freightPrice.doubleValue());
        if (submitBO.getCouponId() != 0) {
            //得到couponUser
            CouponUser couponUser = couponUserMapper.selectByPrimaryKey(submitBO.getCouponId());

            //得到coupon
            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
            //Coupon coupon = couponMapper.selectByPrimaryKey(submitBO.getCouponId());

            couponPrice = coupon.getDiscount();
            if (couponPrice != null) {
                order.setCouponPrice(couponPrice.doubleValue());
            }
            orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        } else {
            orderPrice = goodsPrice.add(freightPrice);
        }
        actualPrice = orderPrice;

        order.setOrderPrice(orderPrice.doubleValue());
        order.setActualPrice(actualPrice.doubleValue());
        order.setId(id);
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        order.setAddTime(date);
        order.setUpdateTime(date);
        order.setDeleted(false);
        order.setComments((short) 0);
        orderMapper.updateByPrimaryKey(order);
        //更新coupon_user表
        if (submitBO.getCouponId() != 0){
            CouponUser couponUser1 = new CouponUser();
            couponUser1.setId(submitBO.getCouponId());
            couponUser1.setStatus((short) 1);
            couponUser1.setOrderId(id);
            Date date1 = new Date();
            couponUser1.setUsedTime(date1);
            couponUser1.setUpdateTime(date1);
            couponUser1.setDeleted(true);
            couponUserMapper.updateByPrimaryKeySelective(couponUser1);
        }

        //返回orderId
        return id;
    }
}
